//
//  PhotoBrowserViewController.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/14.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import SVProgressHUD

private let HZPhotoBrowserCellID = "HZPhotoBrowserCellID"

class PhotoBrowserViewController: UIViewController {
//    MARK:控制器属性
    // 照片URL数组
    var urls:[NSURL]
    // 用户选中照片索引
    var selectedIndexPath:NSIndexPath
    
/// 当前选中的图像索引
    var currentImageIndex:NSIndexPath{
        return collectionView.indexPathsForVisibleItems().last!
    }
    
///  当前选中的图像视图
    var currentImageView:UIImageView{
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex) as! PhotoBrowserCell
        return cell.imageView
    }
    
//    MARK:---保存图像
    @objc private func saveImage(){
//        1.获取图像
//        let path = collectionView.indexPathsForVisibleItems().last!
//        let cell = collectionView.cellForItemAtIndexPath(path) as! PhotoBrowserCell
      
        // 提示:SDWebImage:不一定能下载到图片
        guard let image = currentImageView.image else{
            SVProgressHUD.showInfoWithStatus("没有图像")
            return
        }
//        2.保存图像
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
//    判断是不是保存成功的完成回调方法
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    
//    MARK:---构造函数
    // 好处:简化外部的调用
    // 可以不适用可选项属性,避免后续的解包问题
    init(urls:[NSURL],indexPath:NSIndexPath){
        self.urls = urls
        selectedIndexPath = indexPath
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit{
        print("浏览器88")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print(urls)
        print(selectedIndexPath)
    }
    
//    视图完成布局,准备开始显示
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
//        collectionView滚动到用户选择的图片
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
//        分页控件
        pageControl.currentPage = selectedIndexPath.item
    }
    
//     视图出现---会出现图片的跳跃,先显示第一张,在进行滚动
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
//        collectionView滚动到用户选择的那张图片
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
//    界面设计
    override func loadView() {
//        1.创建全屏的视图
//        let rect = UIScreen.mainScreen().bounds
//        1.创建一个全屏的视图(结构体修改属性需要var,对象不需要)
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        
        view = UIView(frame:rect)
        view.backgroundColor = UIColor.blackColor()
        setupUI()
    }
    
    private func setupUI(){
//        1.添加控件
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        view.addSubview(pageControl)
        
//        2.设置布局
        collectionView.frame = view.bounds
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["saveButton":saveButton,"closeButton":closeButton]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[saveButton(==80)]-(>=8)-[closeButton(==80)]-28-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[closeButton(35)]-8-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[saveButton(35)]-8-|", options: [], metrics: nil, views: viewDict))
        
//        分页控件
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: -10))
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -8))
        
//        3.准备控件
        prepareCollectionView()
        preparPageControl()
        
        // 监听方法---RAC--一但使用self,同时没有取消信号,一定注意循环引用
        closeButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
            self?.dismissViewControllerAnimated(true, completion: nil)
        }
        saveButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext  { [weak self](btn) ->Void in
            self?.saveImage()
            }
        pageControl.rac_signalForControlEvents(.ValueChanged).subscribeNext { [weak self](pageControl) -> Void in
            let indexPath = NSIndexPath(forItem: pageControl.currentPage, inSection: 0)
//            滚动到指定的索引
            self?.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        }
        
        }
    
//    准备分页视图
    private func preparPageControl(){
        pageControl.numberOfPages = urls.count
        // 单页隐藏
        pageControl.hidesForSinglePage = true
        pageControl.pageIndicatorTintColor = UIColor.whiteColor()
        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
    }
    
//    准备CollectionView
    private func prepareCollectionView(){
//        1.注册cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: HZPhotoBrowserCellID)
//        2.数据源
        collectionView.dataSource = self
        collectionView.delegate = self
//        3.设置布局属性
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }

//    MARK:---懒加载控件:
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var saveButton:UIButton = UIButton(title: "保存", fontSize: 14)
    private lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14)
//    分页控件--绝大多数只是用来显示的
    private lazy var pageControl:UIPageControl = UIPageControl()
    
//    照片缩放的比例,swift的extension中不能包含存储型属性
    private var photoScale:CGFloat = 1
}

//   MARK:---UICollectionViewDataSource
extension PhotoBrowserViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
//    提示:indexPath是之前一个cell的索引
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        pageControl.currentPage = collectionView.indexPathsForVisibleItems().last?.item ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HZPhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowserCell
//        cell.backgroundColor = UIColor.randomColor()
        cell.url = urls[indexPath.item]
        cell.photoDelegate = self
        return cell
    }
}

//  MARK:照片cell的代理的实现
extension PhotoBrowserViewController:PhotoBrowserCellDelegate{
    
//    缩放完成
    func photoBrowserCellEndZoom() {
        // 如果缩放比例 < 0.8 dismiss
        if photoScale < 0.8{
            
//            一旦调用了dismiss会触发,animator中接触转场动画方法
//            从当前的动画状态继续完成后续的转场动画
//            交互式转场动画结束,交给系统的转场
            completeTransition(true)
            
        }else{  // 恢复位置
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1.0
                
                }) { _ in
                    
                    // 动画完成后,显示控件
                    self.hideControllers(false)
            }
        }
    }
    
    /// 缩放中
    ///
    /// - parameter scale: 当前的缩放比例
    func photoBrowserCellDidZooming(scale: CGFloat) {
        // 1.记录缩放的比例
        photoScale = scale
        
        // 2.开始交互转场---开始或是隐藏控件
        hideControllers(scale < 1.0)
        
        if scale < 1.0{
            startInteractiveTransition(self)
        }else{
//            恢复形变的参数
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
    }
    
//  显示/隐藏控件
    private func hideControllers(ishidden:Bool){
        closeButton.hidden = ishidden
        saveButton.hidden = ishidden
        pageControl.hidden = (urls.count == 1) ?true :ishidden
        
        view.backgroundColor = ishidden ? UIColor.clearColor():UIColor.blackColor()
        collectionView.backgroundColor = ishidden ? UIColor.clearColor(): UIColor.blackColor()
    }
}

//  MARK:交互式转场的协议
extension PhotoBrowserViewController:UIViewControllerInteractiveTransitioning{
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        self.view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        self.view.alpha = photoScale
    }
}

/// MARK:转场动画上下文---提供转场的动画细节
extension PhotoBrowserViewController:UIViewControllerContextTransitioning{
//    完成转场动画
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView? { return view.superview }
    
    func isAnimated() -> Bool { return true }
    func isInteractive() -> Bool { return true }
    func transitionWasCancelled() -> Bool { return false }
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    func viewForKey(key: String) -> UIView? { return view }
    
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }

}
























































